// Copyright 1998-2014 Epic Games, Inc. All Rights Reserved.

#include "PDA.h"
#include "PDAPlayerController.h"
#include "EngineUserInterfaceClasses.h"

APDAPlayerController::APDAPlayerController(const class FPostConstructInitializeProperties& PCIP)
	: Super(PCIP)
	, AimDirection( 0.0f, 0.0f, 0.0f )
	, AimTurnSpeed(8.0f)
{
}

void APDAPlayerController::PlayerTick( float deltaTime )
{
	Super::PlayerTick(deltaTime);

	UpdateAimDirection(deltaTime);
}

void APDAPlayerController::SetupInputComponent()
{
	// set up gameplay key bindings
	Super::SetupInputComponent();

	InputComponent->BindAxis("MoveForward", this, &APDAPlayerController::OnMoveForward);
	InputComponent->BindAxis("MoveRight", this, &APDAPlayerController::OnMoveRight);

	InputComponent->BindAxis("AimForward", this, &APDAPlayerController::OnAimForward);
	InputComponent->BindAxis("AimRight", this, &APDAPlayerController::OnAimRight);
}

void APDAPlayerController::OnMoveForward( const float value )
{
	if( auto character = GetCharacter() )
	{
		if ( value != 0.0f )
		{
			// find out which way is forward
			const FRotator YawRotation( 0, ControlRotation.Yaw, 0 );

			// get forward vector
			const FVector Direction = FRotationMatrix( YawRotation ).GetUnitAxis(EAxis::X);
			character->AddMovementInput( Direction, value );
		}
	}
}

void APDAPlayerController::OnMoveRight( const float value )
{
	if (auto character = GetCharacter())
	{
		if (value != 0.0f)
		{
			// find out which way is forward
			const FRotator YawRotation(0, ControlRotation.Yaw, 0);

			// get forward vector
			const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y);
			character->AddMovementInput(Direction, value);
		}
	}
}

void APDAPlayerController::OnAimForward(const float value)
{	
	AimDirection.X = value;
}

void APDAPlayerController::OnAimRight(const float value)
{
	AimDirection.Y = value;
}

void APDAPlayerController::UpdateAimDirection(const float deltaTime)
{
	if (AimDirection.Size() > 0.5f)
	{
		if (auto character = GetCharacter())
		{
			const FVector forward(-1.0f, 0.0f, 0.0f);
			const float angle = acos(forward.CosineAngle2D(AimDirection));
			const float angleDegrees = FMath::RadiansToDegrees(angle);
			const float yaw = AimDirection.Y > 0.0f ? angleDegrees : -angleDegrees;

			const FRotator currentRotation = character->GetActorRotation();
			const FRotator targetRotation(0, yaw, 0);

			const FRotator updatedRotation = FMath::RInterpTo(currentRotation, targetRotation, deltaTime, AimTurnSpeed);

			character->SetActorRotation(updatedRotation);
		}
	}
}
